package com.xmy.study.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.xmy.study.entity.Task;
import com.xmy.study.service.IEduClassTypeService;
import com.xmy.study.service.IEduVersionService;
import com.xmy.study.service.ITaskService;
import com.xmy.study.util.Code;
import com.xmy.study.util.PageResult;
import com.xmy.study.util.Result;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDate;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
 * <p>
 * 任务表 前端控制器
 * </p>
 *
 * @author Helin
 * @since 2024-03-18
 */
@RestController
@RequestMapping("/api/admin/task")
public class TaskController {

    @Autowired
    ITaskService iTaskService;

    @Autowired
    IEduClassTypeService iEduClassTypeService;

    @Autowired
    IEduVersionService iEduVersionService;

    @GetMapping("")
    @ApiOperation("查询任务")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "yearPart", value = "年份", required = false, dataType = "String"),
            @ApiImplicitParam(name = "quarterNum", value = "季度", required = false, dataType = "String"),
            @ApiImplicitParam(name = "yearClassId", value = "年级id", required = false, dataType = "String"),
            @ApiImplicitParam(name = "classTypeId", value = "班型id", required = false, dataType = "String"),
            @ApiImplicitParam(name = "taskDate", value = "任务日期", required = false, dataType = "String"),
            @ApiImplicitParam(name = "taskCourseNum", value = "学习到的课次", required = false, dataType = "String"),
            @ApiImplicitParam(name = "courseVersionId", value = "版本", required = false, dataType = "String"),
    })
    public Result searchTask(@RequestParam Map reMap) {
        Integer pageNum = StringUtils.isEmpty((String) reMap.get("pageNum")) ? 1 : Integer.valueOf((String) reMap.get("pageNum"));
        Integer pageSize = StringUtils.isEmpty((String) reMap.get("pageSize")) ? 10 : Integer.valueOf((String) reMap.get("pageSize"));
        Page<Task> iPage = new Page<>(pageNum, pageSize);

        String yearPart = (String) reMap.get("yearPart");
        String quarterNum = (String) reMap.get("quarterNum");
        String yearClassId = (String) reMap.get("yearClassId");
        String classTypeId = (String) reMap.get("classTypeId");
        String taskDate = (String) reMap.get("taskDate");
        String taskCourseNum = (String) reMap.get("taskCourseNum");
        String courseVersionId = (String) reMap.get("courseVersionId");

        QueryWrapper<Task> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq(StringUtils.isNotBlank(yearPart), "year_part", yearPart);
        queryWrapper.eq(StringUtils.isNotBlank(quarterNum), "quarter_num", quarterNum);
        queryWrapper.eq(StringUtils.isNotBlank(courseVersionId), "course_version_id", courseVersionId);
        queryWrapper.eq(StringUtils.isNotBlank(yearClassId), "year_class_id", yearClassId);
        queryWrapper.eq(StringUtils.isNotBlank(taskDate), "task_date", taskDate);
        queryWrapper.eq(StringUtils.isNotBlank(classTypeId), "class_type_id", classTypeId);
        queryWrapper.eq(StringUtils.isNotBlank(taskCourseNum), "task_course_num", taskCourseNum);
        queryWrapper.orderByDesc("task_date", "id");
        queryWrapper.orderByAsc("year_class_id");
        iTaskService.page(iPage, queryWrapper);

        // 在循环外创建缓存
        Map<Long, String> classTypeCache = new HashMap<>();
        Map<Long, String> courseVersionCache = new HashMap<>();

        for (Task task : iPage.getRecords()) {
            if (task.getClassTypeId() != null) {
                //班型中文名
                if (!classTypeCache.containsKey(task.getClassTypeId())) {
                    classTypeCache.put(task.getClassTypeId(), iEduClassTypeService.getById(task.getClassTypeId()).getName());
                }
                task.setClassTypeStr(classTypeCache.get(task.getClassTypeId()));
            }
            if (task.getCourseVersionId() != null) {
                //版本中文名
                if (!courseVersionCache.containsKey(task.getCourseVersionId())) {
                    courseVersionCache.put(task.getCourseVersionId(), iEduVersionService.getById(task.getCourseVersionId()).getName());
                }
                task.setCourseVersionStr(courseVersionCache.get(task.getCourseVersionId()));
            }
        }
        return new Result(Code.GET_OK, new PageResult(iPage.getRecords(), iPage.getTotal(), iPage.getPages()), Code.GET_OK_MSG);
    }

    @PostMapping("")
    @ApiOperation("添加/修改任务")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "任务id", required = true, dataType = "String"),
            @ApiImplicitParam(name = "yearPart", value = "年份", required = true, dataType = "String"),
            @ApiImplicitParam(name = "quarterNum", value = "季度，学期", required = true, dataType = "String"),
            @ApiImplicitParam(name = "yearClassId", value = "年级id", required = true, dataType = "String"),
            @ApiImplicitParam(name = "classTypeId", value = "班型id", required = true, dataType = "String"),
            @ApiImplicitParam(name = "courseVersionId", value = "版本", required = true, dataType = "String"),
            @ApiImplicitParam(name = "taskDate", value = "日期", required = true, dataType = "String"),
            @ApiImplicitParam(name = "taskCourseNum", value = "课次", required = true, dataType = "String"),
            @ApiImplicitParam(name = "breakShutNum", value = "最低学习进度", required = true, dataType = "String")
    })
    public Result createTask(@RequestBody Map map) {
        String id = (String) map.get("id");
        String yearPart = (String) map.get("yearPart");
        Integer quarterNum = (Integer) map.get("quarterNum");
        Integer yearClassId = (Integer) map.get("yearClassId");
        String classTypeId = (String) map.get("classTypeId");
        String taskDate = (String) map.get("taskDate");
        Integer taskCourseNum = (Integer) map.get("taskCourseNum");
        Integer lowestShutNum = (Integer) map.get("lowestShutNum");
        Integer breakShutNum = (Integer) map.get("breakShutNum");
        String courseVersionId = (String) map.get("courseVersionId");

        Task task = new Task();

        QueryWrapper wrapper = new QueryWrapper<>();
        wrapper.eq("year_part", yearPart);
        wrapper.eq("quarter_num", quarterNum);
        wrapper.eq("year_class_id", yearClassId);
        wrapper.eq("class_type_id", classTypeId);
        wrapper.eq("course_version_id", courseVersionId);
        wrapper.eq("task_course_num", taskCourseNum);
        List<Task> tasks = iTaskService.list(wrapper);

        if (StringUtils.isNotBlank(id)) {
            task = iTaskService.getById(id);
            if (Objects.isNull(task)) {
                return new Result(Code.EXP_ERROR, null, "该任务不存在");
            }
            if (tasks.size() > 1) {
                return new Result(Code.ERROR, null, "该任务已存在");
            }
        } else {
            if (!CollectionUtils.isEmpty(tasks)) {
                return new Result(Code.ERROR, null, "该任务已存在");
            }
        }

        task.setYearPart(Integer.valueOf(yearPart));
        task.setQuarterNum(quarterNum);
        task.setYearClassId(yearClassId);
        if (StringUtils.isNotBlank(classTypeId)) {
            task.setClassTypeId(Long.valueOf(classTypeId));
        }
        if (StringUtils.isNotBlank(taskDate)) {
            task.setTaskDate(LocalDate.parse(taskDate));
        }
        task.setTaskCourseNum(taskCourseNum);
        task.setLowestShutnum(lowestShutNum);
        task.setBreakShutnum(breakShutNum);
        if (StringUtils.isNotBlank(courseVersionId)) {
            task.setCourseVersionId(Long.valueOf(courseVersionId));
        }
        task.setDeleted(0);
        iTaskService.saveOrUpdate(task);
        return new Result(Code.OK, null, Code.OK_MSG);
    }

    @DeleteMapping("/{id}")
    @ApiOperation("删除任务")
    @ApiImplicitParam(name = "id", value = "任务id", required = true, dataType = "String")
    public Result deleteTask(@PathVariable(value = "id") String id) {
        Task eduTask = iTaskService.getById(id);
        if (Objects.isNull(eduTask)) {
            return new Result(Code.EXP_ERROR, null, "该任务不存在");
        }
        iTaskService.removeById(Long.parseLong(id));
        return new Result(Code.DELETE_OK, null, Code.DELETE_OK_MSG);
    }

}
